package com.kordar.api.modular.unicomJS;

import com.kordar.api.exception.ErrorType;
import com.kordar.api.exception.ServiceException;
import com.kordar.api.util.JwtTokenUtil;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UnicomjsAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");//
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "86400");
        response.setHeader("Access-Control-Allow-Headers", "token");
        // 如果是OPTIONS请求则结束
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

        String requestURI = request.getRequestURI();
        if (requestURI.equals("/unicomjs/token")) {
            return true;
        }

        String token = request.getHeader("token");

        try {

            if (!JwtTokenUtil.checkToken(token)) {
                throw new ServiceException(ErrorType.TOKEN_ERROR);
            }

            if (JwtTokenUtil.isTokenExpired(token)) {
                throw new ServiceException(ErrorType.TOKEN_EXPIRE);
            }

        } catch (Exception e) {
            throw new ServiceException(ErrorType.TOKEN_ERROR);
        }


        return true;
    }
}
